<?php
if (! isset ( $_SESSION )) {
	@session_start ();
}
function tryLogin($username, $password) {
	require_once "../util/dbconnect.php";
	$result = $db->query ( sprintf ( 'SELECT * FROM `user` WHERE `username` = "%s" AND `password` = "%s"', $username, $password ) );
	if ($result->rowCount () == 1) {
		// correct
		$user_result = $result->fetch ();
		$uid = $user_result ['id'];
		$type = $user_result ['type'];
		$qstr = sprintf ( 'UPDATE `user` SET `last_ip` = "%s" WHERE `id` = %d', $_SERVER ['REMOTE_ADDR'], $uid );
		$db->exec ( $qstr );
		setLoggedIn ( $uid, $username, $type );
		return true;
	} else {
		// wrong username or pwd
		return false;
	}
}
function setLoggedIn($uid, $username, $type='user') {
	$_SESSION ['loggedin'] = true;
	$_SESSION ['uid'] = $uid;
	$_SESSION ['username'] = $username;
	$_SESSION ['type'] = $type;
}
function isLoggedIn() {
	return isset ( $_SESSION ["loggedin"] ) && $_SESSION ["loggedin"] && isset ( $_SESSION ["username"] ) && $_SESSION ["username"] != "";
}
function logout() {
	@session_destroy ();
}
